package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sky.constant.MessageConstant;
import com.sky.dto.UserLoginDTO;
import com.sky.entity.User;
import com.sky.exception.LoginFailedException;
import com.sky.mapper.UserMapper;
import com.sky.properties.WeChatProperties;
import com.sky.service.UserService;
import com.sky.utils.HttpClientUtil;
import com.sky.vo.UserLoginVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private WeChatProperties weChatProperties;

    @Autowired
    private UserMapper userMapper;

    /**
     * 用户微信登录
     *
     * @param dto
     * @return
     */
    @Override
    public User wxLogin(UserLoginDTO dto) {
        // 1.登录凭证校验。根据用户code，获取微信登录用户的openid
        // 请求地址：https://api.weixin.qq.com/sns/jscode2session
        // 请求方式：GET
        Map<String, String> paramMap = new HashMap<>();
        paramMap.put("appid", weChatProperties.getAppid());
        paramMap.put("secret", weChatProperties.getSecret());
        paramMap.put("js_code", dto.getCode());
        paramMap.put("grant_type", "authorization_code");
        String res = HttpClientUtil.doGet("https://api.weixin.qq.com/sns/jscode2session", paramMap);
        log.info("微信端返回的json字符串：{}", res);

        // 2.解析微信端返回的结果
        JSONObject jsonObject = JSON.parseObject(res);
        String openid = jsonObject.getString("openid");
        log.info("openid：{}", openid);

        // 3.判断openid是否为空，如果为空则说明登录失败
        if (openid == null) {
            throw new LoginFailedException(MessageConstant.LOGIN_FAILED);
        }

        // 4.否则，根据openid查询User表，如果登录过新增用户。
        User user = userMapper.getByOpenid(openid);
        if (user == null) {
            user = User.builder()
                    .name(openid.substring(0, 6))
                    .openid(openid)
                    .createTime(LocalDateTime.now())
                    .build();
            userMapper.insert(user);
        }

        // 5.返回User对象
        return user;
    }
}
